<?php
/**
 * CreateTime: 2023/11/28 15:50
 * User:LinQ
 */

namespace App\Func\System;

use App\ApiCall\Gaode\GaodeWebApiExecute;
use App\Func\User\UserFunc;
use App\Models\Logs\CustomersOperateLogModel;
use App\Models\Logs\LoginLogModel;
use App\Models\Logs\OperateLogModel;

class OperateLogFunc
{
    /**该方法通过操作类型和操作者id自动添加操作日志
     * @param $sourceType string 操作类型 Company
     * @param $sourceId int 操作类型的id
     * @param $sourceOpType string 操作的type  Create
     * @param null $callBackInfo 暂时不用 操作的返回值
     */
    public static function addOperate($sourceType,$sourceId,$sourceOpType,$callBackInfo = null,$uid = 0){
        $request = request();
        if(!$uid){
            $userInfo = (new UserFunc())->getLoginInfo();
            $uid = $userInfo['user_id'];
        }
        (new OperateLogModel())->create([
            'owner_id' => $uid,
            'operate_input_data' => json_encode($request->all(),256),
            'operate_output_data' => $callBackInfo,
            'operate_source_id' => $sourceId,
            'operate_type' => strtoupper($sourceOpType),
            'operate_source_type' => strtoupper($sourceType),
        ]);
    }

    /**该方法通过操作类型和操作者id自动添加操作日志
     * @param $sourceType string 操作类型 Company
     * @param $sourceId int 操作类型的id
     * @param $sourceOpType string 操作的type  Create
     * @param null $callBackInfo 暂时不用 操作的返回值
     */
    public static function addCustomersOperate($sourceType,$sourceId,$sourceOpType,$callBackInfo = null,$uid=0){
        $request = request();
        if(!$uid){
            $userInfo = (new UserFunc())->getLoginInfo();
            $uid = $userInfo['user_id'];
        }
        (new CustomersOperateLogModel())->create([
            'owner_id' => $uid,
            'operate_input_data' => json_encode($request->all(),256),
            'operate_output_data' => $callBackInfo,
            'operate_source_id' => $sourceId,
            'operate_type' => strtoupper($sourceOpType),
            'operate_source_type' => strtoupper($sourceType),
        ]);
    }

    public static function loginLog($ownerId,$type){
        $request = request();
        $ip = $request->ip();
        $ipAddress = (new GaodeWebApiExecute())->ipToAddress($ip);
        $address = "位置地址";
        if($ipAddress['status'] == 1){
            $address = $ipAddress['province'].$ipAddress['city'];
        }
        (new LoginLogModel())->create([
            'owner_id' => $ownerId,
            'type' => $type,
            'login_ip' => $request->ip(),
            'login_address' => $address,
            'user_agent' => $request->userAgent()
        ]);
    }
}